package ru.ssau.customerManagement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.ssau.customerManagement.controller.ServerSideController;
import ru.ssau.customerManagement.controller.ServerSideControllerImpl;
import ru.ssau.customerManagement.controller.threads.server.Saver;
import ru.ssau.customerManagement.controller.threads.server.Worker;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by illabefat on 25.11.14.
 */
public class ServerMain {
    private static final Logger logger = LoggerFactory.getLogger(ServerMain.class);

    private static ServerSideController controller;
    private static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        logger.info("Starting...");
        controller = new ServerSideControllerImpl();
        File dump = new File("dump.bin");
        if (dump.exists())
        {
            controller.importModel(dump);
        }

        scheduler.scheduleWithFixedDelay(new Saver(controller), 60, 60, TimeUnit.SECONDS);

        ServerSocket serverSocket = new ServerSocket(5555);

        logger.info("Successfully loaded all stuff");

        while (true)
        {
            Socket client = serverSocket.accept();
            logger.info("Client connected");
            new Thread(new Worker(client, controller)).start();
        }
    }
}
